package com.idol.logger.core.format.utils

import kotlin.math.min

/**
 * 裁剪后有效堆栈信息
 */
internal fun croppedRealStackTrack(
    stackTrack: Array<StackTraceElement>,
    ignorePackage: String,
    maxDepth: Int
): Array<StackTraceElement> = cropStackTrace(realStackTrack(stackTrack, ignorePackage), maxDepth)

/**
 * 有效堆栈信息
 */
private fun realStackTrack(
    stackTrack: Array<StackTraceElement>,
    ignorePackage: String
): Array<StackTraceElement> {
    if (stackTrack.isEmpty() || ignorePackage.isEmpty()) return stackTrack
    var ignoreDepth = 0
    run label@{
        stackTrack.forEach {
            var isIgnore = it.className.startsWith(ignorePackage)
            if (isIgnore) {
                val tail = it.className.replace(ignorePackage, "")
                isIgnore = tail.isEmpty() || tail.startsWith(".")
            }
            if (isIgnore) ignoreDepth++ else return@label
        }
    }
    return stackTrack.copyOfRange(ignoreDepth, stackTrack.size - 1)
}

/**
 * 裁剪堆栈信息
 */
private fun cropStackTrace(
    callStack: Array<StackTraceElement>,
    maxDepth: Int
): Array<StackTraceElement> = callStack.take(min(maxDepth, callStack.size)).toTypedArray()